﻿using System;
using System.ComponentModel;
using System.Xml;
using Aeon.Emulator;

namespace Aeon.Configuration
{
    /// <summary>
    /// Abstract base device configuration implementation.
    /// </summary>
    public abstract class DeviceConfiguration : AeonConfiguration, IDeviceConfiguration
    {
        private bool enabled = true;

        /// <summary>
        /// Initializes a new instance of the DeviceConfiguration class.
        /// </summary>
        /// <param name="deviceName">Name of the device.</param>
        protected DeviceConfiguration(string deviceName)
        {
            if(string.IsNullOrEmpty(deviceName))
                throw new ArgumentNullException("deviceName");

            this.DeviceName = deviceName;
        }

        /// <summary>
        /// Gets the name of the device.
        /// </summary>
        public string DeviceName { get; private set; }

        /// <summary>
        /// Gets or sets a value indicating whether the device is enabled.
        /// </summary>
        public bool IsEnabled
        {
            get
            {
                return this.enabled;
            }
            set
            {
                if(value != this.enabled)
                {
                    this.enabled = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("IsEnabled"));
                }
            }
        }

        /// <summary>
        /// Returns a new instance of the emulated device.
        /// </summary>
        /// <param name="p">Extra parameters which may be used for initialization.</param>
        /// <returns>New instance of the emulated device.</returns>
        public abstract IVirtualDevice Create(CreateDeviceParameters p);
        /// <summary>
        /// Returns a deep copy of the device configuration.
        /// </summary>
        /// <returns>Deep copy of the device configuration.</returns>
        public abstract IDeviceConfiguration Clone();

        /// <summary>
        /// Serializes the configuration to an XML element.
        /// </summary>
        /// <param name="xmlWriter">XmlWriter used to serialize the object.</param>
        protected override void Serialize(XmlWriter xmlWriter)
        {
            xmlWriter.WriteAttributeString("IsEnabled", this.IsEnabled.ToString());
        }
        /// <summary>
        /// Deserializes the configuration from an XML element.
        /// </summary>
        /// <param name="xmlReader">XmlReader used to deserialize the object.</param>
        protected override void Deserialize(XmlReader xmlReader)
        {
            bool enabled;
            if(!bool.TryParse(xmlReader.GetAttribute("IsEnabled") ?? string.Empty, out enabled))
                enabled = true;
            this.IsEnabled = enabled;
        }
    }
}
